package com.xiaoshou.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;

import com.xiaoshou.pojo.Files;


public class FileUtil {

	public static String getFileSize(long filesize) {
		if (filesize > (1024 * 1024 * 1024)) {
			return String.valueOf((float) (filesize / (1024 * 1024 * 1024)))
					+ "GB";
		} else if (filesize > (1024 * 1024)) {
			return String.valueOf((float) (filesize / (1024 * 1024))) + "MB";
		} else if (filesize > 1024) {
			return String.valueOf((float) (filesize / 1024)) + "KB";
		} else {
			return String.valueOf((float) filesize) + "B";
		}
	}

	public static List<Files> convertFileSize(List<Files> file) {
		List<Files> files = new ArrayList<Files>();
		for (Files filess : file) {
			filess.setFilesize(getFileSize(Long.parseLong(filess.getFilesize())));
			files.add(filess);
		}
		return files;
	}

	public static void copyFile(String filepath, File file) {
		try {

			BufferedOutputStream out = new BufferedOutputStream(
					new FileOutputStream(new File(filepath)));
			BufferedInputStream in = new BufferedInputStream(
					new FileInputStream(file));

			byte[] buffer = new byte[1024];
			int length = -1;
			while ((length = in.read(buffer)) != -1) {
				out.write(buffer, 0, length);
			}
			out.flush();
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getMd5OfFile(String filepath){
		String mmd5 = "";
		try {
			mmd5 = DigestUtils.md5Hex(new FileInputStream(filepath));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mmd5;
	}
}